package BandB.Tool.GPhoneManager.TaskManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import BandB.Tool.GPhoneManager.R;
import BandB.Tool.GPhoneManager.TaskManager.Util.DataHandler;
import BandB.Tool.GPhoneManager.TaskManager.Util.Utilities;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

//import com.mgeek.android.ads.AdView;

public class ProcessList extends Activity {
	public static final int LOADING_START = 0;
	public static final int LOADING_END = 1;
	public static final int CACHE_UPDATED = 2;
	public static final int LOADING_DIALOG = 0;
	public static final int MENU_END_PROCESS = 0;
	public static final int MENU_SWITH_TO = 1;
	public static final int MENU_DETAIL = 2;
	public static final int MENU_UNINSTALL = 3;
	public static final int MENU_CPU_USAGE = 4;
	/**
	 * to distinguish from blacklist or not
	 */
	public static final int MENU_CHANGE_TYPE = 5;

	public static final int UNINSTALL_CODE = 1;
	public static final int TIME_SETTING = 2;

	public static final int MENU_REFRESH = 0;
	public static final int MENU_PERFORMANCE = 1;
	public static final int MENU_SETTING = 2;
	public static final int MENU_BATCH_TERMINATE = 3;
	public static final int MENU_BATCH_UNINSTALL = 4;
	public static final int MENU_TERMINATE_ALL = 5;
	public static final int MENU_APP_BLACKLIST_MANAGER = 6;
	private static final int MENU_SHOW_TASK_KILLER = 7;
	// public static final int MENU_KILL_ALL_BLACK_LIST_APP = 7;
	// public static final int MENU_SCHEDULE_TERMINATE_APPS = 8;

	public static final int DETAIL_DIALOG = 1;
	public static final int PERFORMANCE_DIALOG = 2;
	public static final int KEY_SETTING_DIALOG = 3;
	public static final int CPU_USAGE_DIALOG = 4;
	private static final String TAG = "AppListActivity";
	private Process process;

	private static final String MOVE_TO_BLACKLIST = "Move to blacklist";
	private static final String REMOVE_FROM_BLACKLIST = "Remove from blacklist";
	private TextView memoryTextView, userTextView, systemTextView;
	private static String available_memory, cpuUser, cpuSystem;
	private static final byte[] SYNC = new byte[0];
	private static String status;
	private static ActivityManager activityManager;

	private Thread loadingThread = null;
	private Thread refreshThread = null;
	ApplicationsAdapter adapter;
	Dialog detailDialog, perfomanceDialog;
	ApplicationInfo currentAppInfo;
	String systemInfoCache = null;
	Object sync = new Object();
	Map<String, String> sizeCache = new HashMap<String, String>();
	private DataHandler dataHandler;
	private ListView taskListView;
	private TextView loadingTextView;
	private boolean isRunning;
	public static final String ANDROID_SYSTEM = "android";
	protected static final int MSG_REFRESH_STATUS = 11;
	private Timer timerGetCache, timerGetStatus;
	private TimerTask taskGetCache, taskGetStatus;

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
				.getMenuInfo();
		ApplicationInfo info = (ApplicationInfo) taskListView.getAdapter()
				.getItem(menuInfo.position);
		String packageName = info.appInfo.packageName;
		switch (item.getItemId()) {
		case MENU_END_PROCESS:
			try {
				if (dataHandler.IsSystemProcess(info.appInfo.packageName)) {

					Toast.makeText(
							ProcessList.this,
							"Can't stop application: "
									+ info.appInfo.packageName
									+ ", it is a system process",
							Toast.LENGTH_SHORT).show();
					return true;
				}
				ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
				am.restartPackage(info.appInfo.packageName);
			} catch (Exception e) {
				Log
						.e("AppListActivity", "killProcess error:"
								+ e.toString(), e);
			}
			// ((ApplicationsAdapter)getListAdapter()).remove(info);
			handler.sendEmptyMessageDelayed(LOADING_START, 200);
			return true; /* true means: "we handled the event". */
		case MENU_SWITH_TO:
			try {
				Intent intent = new Intent();
				intent.setComponent(info.topActivity);
				// intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
			} catch (Exception e) {
				// TODO: handle exception
				Log.e(TAG, "switch to error:" + e.toString());
			}
			return true; /* true means: "we handled the event". */
		case MENU_DETAIL:
			currentAppInfo = info;
			showDialog(DETAIL_DIALOG);
			return true; /* true means: "we handled the event". */
		case MENU_CPU_USAGE:
			currentAppInfo = info;
			showDialog(CPU_USAGE_DIALOG);
			return true;
		case MENU_UNINSTALL:
			Uri uri = Uri.fromParts("package", info.appInfo.packageName, null);
			Intent uninstallPackageIntent = new Intent(Intent.ACTION_DELETE,
					uri);
			startActivityForResult(uninstallPackageIntent, UNINSTALL_CODE);
			handler.sendEmptyMessageDelayed(LOADING_START, 200);
			return true;
			/**
			 * add a application to blacklist or remove from it
			 */
		case MENU_CHANGE_TYPE:
			boolean isSuccessful = false;
			if (item.getTitle().equals(MOVE_TO_BLACKLIST)) {
				try {
					isSuccessful = dataHandler.moveToBlacklist(packageName);
				} catch (Exception e) {
					// TODO: handle exception
				}
				if (isSuccessful) {
					Toast.makeText(this,
							"Succeed to move " + info.title + " to blacklist",
							Toast.LENGTH_LONG).show();
				} else {
					Toast
							.makeText(
									this,
									new StringBuilder().append("Fail to move ")
											.append(info.title).append(
													" to blacklist,").append(
													info.title).append(
													" is a system process.")
											.toString(), Toast.LENGTH_LONG)
							.show();
				}
			} else {
				try {
					dataHandler.removeFromBlacklist(packageName);
				} catch (Exception e) {
					// TODO: handle exception
					Log.e(TAG, "remove from blacklist failed");
					Toast.makeText(this,
							"Fail to remove this application from blacklist.",
							Toast.LENGTH_LONG).show();
					return true;
				}
				Toast.makeText(this,
						"Succeed to remove this application from blacklist.",
						Toast.LENGTH_LONG).show();
			}

			return true;
		}
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case UNINSTALL_CODE:
			handler.sendEmptyMessage(LOADING_START);
			break;
		case TIME_SETTING:
			// startService(new Intent(this, ScheduleService.class));
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_list);
		dataHandler = new DataHandler(this);
		isRunning = true;
		// mContext = this;
		// taskListView = getListView();
		memoryTextView = (TextView) findViewById(R.id.txtViewMemory);
		userTextView = (TextView) findViewById(R.id.txtViewUser);
		systemTextView = (TextView) findViewById(R.id.txtViewSystem);
		taskListView = (ListView) findViewById(R.id.list);
		taskListView
				.setOnCreateContextMenuListener(onCreateContextMenuListener);
		taskListView.setTextFilterEnabled(true);
		taskListView.setOnItemClickListener(listOnItemClickListener);
		loadingTextView = (TextView) findViewById(R.id.task_loading_tag);

		activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

		handler.sendEmptyMessage(LOADING_START);
		// startService(new Intent(this, ScheduleService.class));
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e(TAG, "resume");

		timerGetCache = new Timer();
		taskGetCache = generateGetCacheTask();
		timerGetCache.schedule(taskGetCache, 0, 5000);

		timerGetStatus = new Timer();
		taskGetStatus = generateGetStatusTask();
		timerGetStatus.schedule(taskGetStatus, 1000, 5000);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.e(TAG, "pause");
		try {
			taskGetCache.cancel();
			timerGetCache.cancel();
			timerGetCache = null;

			taskGetStatus.cancel();
			timerGetStatus.cancel();
			taskGetStatus = null;
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "cancel tasks error:" + e.getMessage());
		}
		super.onPause();
	}

	OnItemClickListener listOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			((ApplicationsAdapter) taskListView.getAdapter())
					.setCheckAt(position);
		}

	};

	OnCreateContextMenuListener onCreateContextMenuListener = new OnCreateContextMenuListener() {

		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
			ApplicationInfo info = (ApplicationInfo) taskListView.getAdapter()
					.getItem(adapterContextMenuInfo.position);
			menu.setHeaderTitle("Select operation for " + info.title);
			menu.add(0, MENU_END_PROCESS, 0, R.string.end_process);
			if (info.getTopActivity() != null) {
				menu.add(0, MENU_SWITH_TO, 1, R.string.switch_to);
			}
			menu.add(0, MENU_CPU_USAGE, 2, R.string.cpu_usage);
			menu.add(0, MENU_DETAIL, 3, R.string.detail);
			menu.add(0, MENU_UNINSTALL, 4, R.string.uninstall);
			if (dataHandler.isBlack(info.appInfo.packageName)) {
				menu.add(0, MENU_CHANGE_TYPE, 5, REMOVE_FROM_BLACKLIST);
			} else {
				menu.add(0, MENU_CHANGE_TYPE, 5, MOVE_TO_BLACKLIST);
			}
		}

	};

	public List<ApplicationInfo> getCheckedTask() {
		List<ApplicationInfo> list = new ArrayList<ApplicationInfo>();

		ApplicationsAdapter listAdapter = (ApplicationsAdapter) taskListView
				.getAdapter();

		for (int i = 0; i < listAdapter.getCount(); i++) {
			ApplicationInfo oneTask = listAdapter.getItem(i);
			if (oneTask.isCheck) {
				list.add(oneTask);
			}

		}

		return list;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_REFRESH, 1, R.string.refresh).setIcon(
				R.drawable.ic_menu_refresh);
//		menu.add(0, MENU_PERFORMANCE, 0, R.string.performance).setIcon(
//				R.drawable.ic_menu_performance);
		// menu.add(0,
		// MENU_SETTING,0,R.string.menu_setting).setIcon(R.drawable.ic_menu_setting);
		menu.add(0, MENU_BATCH_TERMINATE, 0, R.string.task_batch_terminate)
				.setIcon(R.drawable.ic_menu_setting);
		// menu.add(0, MENU_BATCH_UNINSTALL, 0, R.string.task_batch_uninstall)
		// .setIcon(R.drawable.ic_menu_setting);
		menu.add(0, MENU_TERMINATE_ALL, 0, R.string.terminate_all).setIcon(
				R.drawable.ic_menu_setting);
		menu.add(0, MENU_APP_BLACKLIST_MANAGER, 0, R.string.blacklist_manager)
				.setIcon(R.drawable.ic_menu_notifications);
		menu.add(0, MENU_SHOW_TASK_KILLER, 0, "Taskiller");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_SHOW_TASK_KILLER:
			Intent killerIntent = new Intent(this, ProcessGrid.class);
			killerIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(killerIntent);
			break;
		case MENU_APP_BLACKLIST_MANAGER:
			List<ApplicationInfo> selected = getCheckedTask();
			for (ApplicationInfo info : selected) {
				try {
					dataHandler.moveToBlacklist(info.appInfo.packageName);
				} catch (Exception e) {
					Log.e(TAG, e.getMessage());
				}

			}
			Toast.makeText(this,
					"Move " + selected.size() + " applications to blacklist.",
					Toast.LENGTH_SHORT).show();
			break;
		case MENU_REFRESH:
			handler.sendEmptyMessage(LOADING_START);
			return true;
		case MENU_PERFORMANCE:
			showDialog(PERFORMANCE_DIALOG);
			return true;
		case MENU_SETTING:
			showDialog(KEY_SETTING_DIALOG);
			return true;
		case MENU_BATCH_TERMINATE:
			List<ApplicationInfo> checkList = getCheckedTask();
			if (checkList.size() == 0) {
				Toast.makeText(this, R.string.task_no_item_selected,
						Toast.LENGTH_LONG).show();
				break;
			}
			for (int i = 0; i < checkList.size(); i++) {
				try {
					if (dataHandler
							.IsSystemProcess(checkList.get(i).appInfo.packageName)) {
						Toast.makeText(
								ProcessList.this,
								"Can't stop application: "
										+ checkList.get(i).title
										+ ", it is a system process",
								Toast.LENGTH_SHORT).show();
						continue;
					}
					ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
					am.restartPackage(checkList.get(i).appInfo.packageName);
				} catch (Exception e) {
					Log.e("AppListActivity", "killProcess error:"
							+ e.toString(), e);
				}
			}

			// ((ApplicationsAdapter)getListAdapter()).remove(info);
			handler.sendEmptyMessageDelayed(LOADING_START, 200);

			break;
		case MENU_BATCH_UNINSTALL:
			List<ApplicationInfo> checkList2 = getCheckedTask();
			if (checkList2.size() == 0) {
				Toast.makeText(this, R.string.task_no_item_selected,
						Toast.LENGTH_LONG).show();
				break;
			}
			for (int i = 0; i < checkList2.size(); i++) {
				Uri uri = Uri.fromParts("package",
						checkList2.get(i).appInfo.packageName, null);
				Intent uninstallPackageIntent = new Intent(
						Intent.ACTION_DELETE, uri);
				startActivityForResult(uninstallPackageIntent, UNINSTALL_CODE);
			}

			handler.sendEmptyMessageDelayed(LOADING_START, 200);
			break;
		case MENU_TERMINATE_ALL:
			List<ApplicationInfo> allList = ((ApplicationsAdapter) taskListView
					.getAdapter()).getMAppsList();
			String currentPackage = getPackageName();
			for (int i = 0; i < allList.size(); i++) {
				if (allList.get(i).appInfo.packageName.equals(currentPackage)
						|| allList.get(i).appInfo.packageName
								.equals(ProcessList.ANDROID_SYSTEM)) {
					continue;
				}

				try {
					ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
					am.restartPackage(allList.get(i).appInfo.packageName);
					handler.sendEmptyMessageDelayed(LOADING_START, 200);
				} catch (Exception e) {

					Log.e("AppListActivity", "killProcess error:"
							+ e.toString(), e);
				}
			}

			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case LOADING_DIALOG:
			ProgressDialog pd = new ProgressDialog(this);
			pd.setMessage(getResources().getString(R.string.loading));
			pd.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface arg0) {
					if (null != loadingThread) {
						loadingThread.stop();
					}
				}

			});
			return pd;

		case DETAIL_DIALOG:
			LayoutInflater factory = LayoutInflater.from(this);
			final View detailView = factory.inflate(R.layout.detail, null);
			detailDialog = new AlertDialog.Builder(this).setView(detailView)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									dismissDialog(DETAIL_DIALOG);
								}
							}).create();
			return detailDialog;
		case CPU_USAGE_DIALOG:
			LayoutInflater factory2 = LayoutInflater.from(this);
			final View detailView2 = factory2.inflate(R.layout.detail, null);
			return new AlertDialog.Builder(this).setView(detailView2)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									dismissDialog(CPU_USAGE_DIALOG);
								}
							}).create();
		case PERFORMANCE_DIALOG:
			factory = LayoutInflater.from(this);
			final View perfomanceView = factory.inflate(R.layout.detail, null);
			perfomanceDialog = new AlertDialog.Builder(this).setView(
					perfomanceView).setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							dismissDialog(PERFORMANCE_DIALOG);
						}
					}).create();
			return perfomanceDialog;
		case KEY_SETTING_DIALOG:

			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case LOADING_START:
			break;
		case DETAIL_DIALOG:
			TextView textView = (TextView) dialog.findViewById(R.id.textview);
			String size = null;
			if (sizeCache.containsKey(currentAppInfo.appInfo.packageName)) {
				size = sizeCache.get(currentAppInfo.appInfo.packageName);
			} else {
				long packageSize = new File(currentAppInfo.appInfo.sourceDir)
						.length();
				size = Utilities.formateSize(packageSize);
				sizeCache.put(currentAppInfo.appInfo.packageName, size);
			}

			String text = "Label:" + currentAppInfo.title + "\n"
					+ "Package name:" + currentAppInfo.appInfo.packageName
					+ "\n" + "Process name:"
					+ currentAppInfo.appInfo.processName + "\n" + "Size:"
					+ size;

			textView.setText(text);
			break;
		case CPU_USAGE_DIALOG:
			TextView textView2 = (TextView) dialog.findViewById(R.id.textview);
			RuntimeInfo info;
			synchronized (sync) {
				info = Utilities.getCpuUsageByPid(currentAppInfo.pid,
						systemInfoCache);
			}
			String text2 = "CPU usage:" + info.getCpuUsage() + "%\n"
					+ "Thread count:" + info.getThreadCount() + "\n" + "RSS:"
					+ Utilities.formateSize(info.getMemoryUsage());

			textView2.setText(text2);
			break;
		case PERFORMANCE_DIALOG:
			textView = (TextView) dialog.findViewById(R.id.textview);
			ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
			((ActivityManager) getSystemService(ACTIVITY_SERVICE))
					.getMemoryInfo(mi);
			text = "";
			String cpu = "";
			synchronized (sync) {
				cpu = Utilities.getAllCpuUsage(systemInfoCache);
			}
			try {
				text += "CPU:" + cpu + "\n" + "AvailMem:"
						+ Utilities.formateSize(mi.availMem) + "\n"
						+ "Threshold :" + Utilities.formateSize(mi.threshold)
						+ "\n" + "LowMemory:" + mi.lowMemory;
			} catch (Exception e) {
				Log.e("AppListActivity", e.toString());
			}
			textView.setText(text);
			break;
		default:

			break;
		}
		super.onPrepareDialog(id, dialog);
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOADING_START:
				// showDialog(LOADING_DIALOG);
				loadingThread = new Thread(new Runnable() {
					@Override
					public void run() {
						ArrayList<ApplicationInfo> apps = Utilities
								.getRunningAppList(ProcessList.this);
						synchronized (sync) {
							adapter = new ApplicationsAdapter(ProcessList.this,
									apps);
						}

						loadingThread = null;
						handler.sendEmptyMessage(LOADING_END);
						if (refreshThread == null) {
							refreshThread = new Thread(refresh);
							refreshThread.start();
						}
					}
				});
				loadingThread.start();
				break;
			case LOADING_END:
				// dismissDialog(LOADING_DIALOG);
				taskListView.setAdapter(adapter);
				loadingTextView.setVisibility(View.GONE);
				break;
			case CACHE_UPDATED:

				break;
			case MSG_REFRESH_STATUS:
				refreshStatusBar();
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	Runnable refresh = new Runnable() {

		@Override
		public void run() {
			while (isRunning) {
				try {
					String cache = "";
					BufferedReader br = null;
					String cmd = "top -n 1";
					Process process;
					Runtime runtime = Runtime.getRuntime();
					process = runtime.exec(cmd);
					InputStream is = process.getInputStream();
					InputStreamReader isr = new InputStreamReader(is);
					br = new BufferedReader(isr);

					String line;
					while ((line = br.readLine()) != null) {
						cache += line + "\n";
					}
					synchronized (sync) {
						systemInfoCache = cache;
					}
					handler.sendEmptyMessage(CACHE_UPDATED);
					Thread.sleep(2000);
				} catch (Exception e) {
					e.fillInStackTrace();
					Log.e("Process Manager", "Unable to execute top command");
				}
			}
		}

	};

	@Override
	protected void onDestroy() {
		isRunning = false;
		super.onDestroy();
	}

	private TimerTask generateGetCacheTask() {
		return new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					String cache = "";
					BufferedReader br = null;
					String cmd = "top -n 1";
					Runtime runtime = Runtime.getRuntime();
					process = runtime.exec(cmd);
					InputStream is = process.getInputStream();
					InputStreamReader isr = new InputStreamReader(is);
					br = new BufferedReader(isr);
					String line;
					while ((line = br.readLine()) != null) {
						cache += line + "\n";
					}
					synchronized (SYNC) {
						status = cache;
					}
				} catch (IOException e) {
					// TODO: handle exception
					e.printStackTrace();
					Log.e(TAG, "get status cathe string error.");
				}
			}
		};
	}

	private TimerTask generateGetStatusTask() {
		return new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					String cache = "";
					BufferedReader br = null;
					String cmd = "top -n 1";
					Runtime runtime = Runtime.getRuntime();
					process = runtime.exec(cmd);
					InputStream is = process.getInputStream();
					InputStreamReader isr = new InputStreamReader(is);
					br = new BufferedReader(isr);
					String line;
					while ((line = br.readLine()) != null) {
						cache += line + "\n";
					}
					synchronized (SYNC) {
						status = cache;
						String cpu = Utilities.getAllCpuUsage(status);
						Log.e(TAG, "cpu:" + cpu);
						Pattern pUser = Pattern.compile("User (.*?),");
						Pattern pSystem = Pattern.compile("System (.*?),");
						Matcher mUser = pUser.matcher(cpu);
						Matcher mSystem = pSystem.matcher(cpu);
						if (mUser.find()) {
							cpuUser = mUser.group(1);
						} else {
							cpuUser = "0%";
						}
						if (mSystem.find()) {
							cpuSystem = mSystem.group(1);
						} else {
							cpuSystem = "0%";
						}
						MemoryInfo outInfo = new MemoryInfo();
						activityManager.getMemoryInfo(outInfo);
						available_memory = Utilities
								.formateSize(outInfo.availMem);
						handler.sendEmptyMessage(MSG_REFRESH_STATUS);
					}
				} catch (IOException e) {
					// TODO: handle exception
					e.printStackTrace();
					Log.e(TAG, "get status cathe string error.");
				}
			}
		};
	}

	private void refreshStatusBar() {
		memoryTextView.setText(available_memory);
		userTextView.setText(cpuUser);
		systemTextView.setText(cpuSystem);
	}
}
